import 'package:erp/data/api/user_api.dart';
import 'package:erp/main_state.dart';
import 'package:erp/routes/app_pages.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {
  var username = "".obs;
  var password = "".obs;
  var showPassword = false.obs;

  var usernameTextEditingController = new TextEditingController().obs;
  var passwordTextEditingController = new TextEditingController().obs;

  FocusNode usernameFocusNode = new FocusNode();
  FocusNode passwordFocusNode = new FocusNode();

  LoginController();

  @override
  void onInit() {
    super.onInit();
  }

  void onUsernameChanged(String username) {
    this.username.value = username;
  }

  void onPasswordChanged(String password) {
    this.password.value = password;
  }

  void clearUsername() {
    this.usernameTextEditingController.value.text = "";
    this.username.value = "";
  }

  void clearPassword() {
    this.passwordTextEditingController.value.text = "";
    this.password.value = "";
  }

  void changeShowPassword() {
    showPassword.value = !this.showPassword.value;
  }

  submit() async {
    usernameFocusNode.unfocus();
    passwordFocusNode.unfocus();
    if (username.value.isBlank!) {
      EasyLoading.showInfo("用户/工号 不能为空");
      return;
    }
    if (password.value.isBlank!) {
      EasyLoading.showInfo("密码 不能为空");
      return;
    }
    try {
      var ms = Get.find<MainState>();
      EasyLoading.show(status: '登陆中...');
      var data = await LoginApi.login(username.value, password.value);
      EasyLoading.showSuccess('登陆成功!');
      ms.setAuth(data);
      Get.offAndToNamed(Routes.MAIN);
    } on Exception {}
  }
}
